import { buildTree, findAncestors } from '@/common/utils/tools';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateDeptDto } from './dto/create-dept.dto';
import { UpdateDeptDto } from './dto/update-dept.dto';
import { SysDept } from './entities/dept.entity';
import { IdsDto } from '@/common/dto/ids.dto';
import { SearchDeptDto } from './dto/search-dept.dto';
import {
  queryBuilderAndWhereEQ,
  queryBuilderAndWhereLike,
} from '@/common/utils/db.andwhere';

@Injectable()
export class DeptsService {
  constructor(
    @InjectRepository(SysDept)
    private readonly deptsRepository: Repository<SysDept>,
  ) {}
  async create(data: CreateDeptDto) {
    // 获取部门祖先ids
    const treePath = await findAncestors<SysDept>(
      this.deptsRepository,
      data.parentId,
    );
    data.treePath = treePath.join(',');

    // repository
    const deptTemp = this.deptsRepository.create(data);
    return this.deptsRepository.save(deptTemp);
  }

  findAll(query: SearchDeptDto) {
    const queryBuilder = this.deptsRepository
      .createQueryBuilder('sys_dept')
      .where('1=1');

    const likeProps = {
      'sys_dept.name': query.keywords,
    };
    const likeQueryBuild = queryBuilderAndWhereLike<SysDept>(
      queryBuilder,
      likeProps,
    );
    const eqProps = {
      'sys_dept.status': query.status,
    };
    const eqQueryBuild = queryBuilderAndWhereEQ<SysDept>(
      likeQueryBuild,
      eqProps,
    );

    return eqQueryBuild.getMany();
  }

  async findOne(id: number) {
    return await this.deptsRepository.findOne({ where: { id: String(id) } });
  }

  async update(id: number, data: UpdateDeptDto) {
    // 获取部门祖先ids
    if (data.parentId) {
      const treePath = await findAncestors<SysDept>(
        this.deptsRepository,
        data.parentId,
      );
      data.treePath = treePath.join(',');
    }

    return await this.deptsRepository.update(id, data);
  }

  remove({ ids }: IdsDto) {
    return this.deptsRepository.softDelete(ids.split(','));
  }

  async findTree() {
    const result = await this.deptsRepository.find();
    return buildTree(result);
  }
}
